package by.pavlyukevich.paymentsystem.login;

import javax.servlet.http.HttpServletRequest;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.http.handler.RedirectRequestHandler;

import by.pavlyukevich.paymentsystem.datamodel.user.UserAccount;
import by.pavlyukevich.paymentsystem.webapp.BasicAuthenticationSession;
import by.pavlyukevich.paymentsystem.webapp.WicketWebApplication;

public class LoginLogoutPanel extends Panel {

	public LoginLogoutPanel(String id) {
		super(id);
	}

	@Override
	protected void onInitialize() {
		super.onInitialize();
		boolean isLogged = BasicAuthenticationSession.get().isSignedIn();

		add(new Link<Void>("login-btn") {
			@Override
			protected void onConfigure() {
				super.onConfigure();
				boolean isLoginPage = LoginPage.class.equals(getPage().getClass());
				setVisible(!(isLogged || isLoginPage));
			}

			@Override
			public void onClick() {
				setResponsePage(new LoginPage());
			}
		});

		add(new Link<Void>("logout-btn") {
			@Override
			protected void onConfigure() {
				super.onConfigure();
				setVisible(BasicAuthenticationSession.get().isSignedIn());
			}

			@Override
			public void onClick() {
				final HttpServletRequest servletReq = (HttpServletRequest) getRequest()
						.getContainerRequest();
				servletReq.getSession().invalidate();
				getSession().invalidate();
				getRequestCycle().scheduleRequestHandlerAfterCurrent(
						new RedirectRequestHandler(WicketWebApplication.LOGIN_URL));

			}
		});

		UserAccount userAccount = BasicAuthenticationSession.get().getUserAccount();
		if (isLogged) {
			add(new Label("userName", new Model<String>(
					userAccount.getIndividual() != null ? userAccount.getIndividual().getName()
							+ " " + userAccount.getIndividual().getFamily() : userAccount
							.getContractor().getName())));
		} else {
			add(new Label("userName", new Model<String>("")));
		}

	}
}
